package com.ad.pet.common.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.ad.pet.common.structure.events.Events;
import com.ad.pet.common.structure.events.RxBus;


/**
 * Created by z on.
 * Des:网络状态的广播
 * Date: 2017/6/8
 */
public class NetworkReceiver extends BroadcastReceiver {
    public final static int STATE_MOBILE = 2;
    public final static int STATE_NO_NETWORK = 1;
    public final static int STATE_WIFI = 3;

    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo.State wifiState = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
        NetworkInfo.State mobileState = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
        if (wifiState != null && mobileState != null
                && NetworkInfo.State.CONNECTED != wifiState
                && NetworkInfo.State.CONNECTED == mobileState) {
            // 手机网络连接成功
            RxBus.getDefault().post(new Events.NetWorkStateEvent(STATE_MOBILE));
        } else if (wifiState != null && mobileState != null
                && NetworkInfo.State.CONNECTED != wifiState
                && NetworkInfo.State.CONNECTED != mobileState) {
            // 手机没有任何的网络
            RxBus.getDefault().post(new Events.NetWorkStateEvent(STATE_NO_NETWORK));
        } else if (wifiState != null && NetworkInfo.State.CONNECTED == wifiState) {
            // 无线网络连接成功
            RxBus.getDefault().post(new Events.NetWorkStateEvent(STATE_WIFI));
        }
    }
}
